package com.practice.concurrency;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierMain {

	private static int[] timeWalk = { 5, 8, 15, 15, 10 };
	private static int[] timeSelf = { 1, 3, 4, 4, 5 };
	private static int[] timeBus = { 2, 4, 6, 6, 7 };

	public static void main(String[] args) {
		CyclicBarrier barrier = new CyclicBarrier(3);
		ExecutorService service = Executors.newFixedThreadPool(3);
		service.submit(new Tour(barrier, "Walk Tour", timeWalk));
		service.submit(new Tour(barrier, "Self Tour", timeSelf));
		service.submit(new Tour(barrier, "Bus Tour", timeBus));
		service.shutdown();
	}

}

class Tour implements Runnable {
	private int[] times;
	private CyclicBarrier barrier;
	private String tourName;

	public Tour(CyclicBarrier barrier, String tourName, int[] times) {
		this.barrier = barrier;
		this.tourName = tourName;
		this.times = times;
	}

	public void run() {
		try {
			Thread.sleep(times[0] * 1000);
			System.out.println(now() + ": " + tourName + " reached A");
			barrier.await();
			Thread.sleep(times[1] * 1000);
			System.out.println(now() + ": " + tourName + " reached B");
			barrier.await();
			Thread.sleep(times[2] * 1000);
			System.out.println(now() + ": " + tourName + " reached C");
			barrier.await();
			Thread.sleep(times[3] * 1000);
			System.out.println(now() + ": " + tourName + " reached D");
			barrier.await();
			Thread.sleep(times[4] * 1000);
			System.out.println(now() + ": " + tourName + " reached E");
			barrier.await();
		} catch (InterruptedException | BrokenBarrierException ex) {
			ex.printStackTrace();
		}
	}

	private String now() {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		return sdf.format(new Date());
	}
}
